package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.Address;
import com.itljm.cxrMarket.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author ljm
 * @date 2025/4/9 21:40
 */
@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 新增地址
     */
    @PostMapping("/add")
    public Result<Address> save(@RequestBody Address address) {
        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        addressService.save(address);
        return Result.ok(address);
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        addressService.removeById(id);
        return Result.ok("删除成功");
    }

    /**
     * 修改地址
     */
    @PostMapping("/update")
    public Result<Address> update(@RequestBody Address address) {
        address.setUpdateTime(new Date());
        boolean b = addressService.updateById(address);
        if (b){
            return Result.ok("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }

    /**
     * 查询用户所有地址
     */
    @GetMapping("/list/{userId}")
    public Result<List<Address>> list(@PathVariable String userId) {
        List<Address> list = addressService.getByUserId(userId);
        return Result.ok(list);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default/{id}/{userId}")
    public Result<String> setDefault(@PathVariable Long id, @PathVariable String userId) {
        addressService.setDefault(id, userId);
        return Result.ok("设置成功");
    }

    /**
     * 取消默认地址
     */
    @PutMapping("/cancelDefault/{id}/{userId}")
    public Result<String> cancelDefault(@PathVariable Long id, @PathVariable String userId) {
        addressService.cancelDefault(id, userId);
        return Result.ok("取消成功");
    }

    /**
     * 根据ID查询地址详情
     */
    @GetMapping("/{id}")
    public Result<Address> getById(@PathVariable Long id) {
        Address address = addressService.getById(id);
        return Result.ok(address);
    }

    // 获取默认地址
    @GetMapping("/default/{userId}")
    public Result<Address> getDefault(@PathVariable String userId) {
        Address address = addressService.getDefault(userId);
        if (address == null) {
            return Result.fail("默认地址不存在");
        } else {
            return Result.ok(address);
        }
    }
}
